import { init } from 'snabbdom/build/package/init'
import { h } from 'snabbdom/build/package/h'

import { styleModule } from 'snabbdom/build/package/modules/style'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners'

const patch = init([
  styleModule,
  eventListenersModule
])

var data = [
  {sn: 1, title: '风灵玉秀', desc: '百合番武侠番真好看'},
  {sn: 2, title: '堀与宫村', desc: '吃狗粮吃到饱'},
  {sn: 3, title: '关于我转生变成史莱姆这档事', desc: '在异世界混的风生水起的史莱姆'},
  {sn: 4, title: '在魔王城说晚安 ', desc: '原来公主才是真正的魔王'},
  {sn: 5, title: '入间同学入魔了 ', desc: '入间小天使啊啊啊,女装是真的可爱啊'},
]

var dataLength = data.length
var sortByRule = 'sn'

function listShow (data) {
  return h('li', { 
    style: {  
      listStyle: 'none',
      textAlign: 'left',
      height: '40px'
    } 
  }, [
    h('span.sn', data.sn),
    h('span.title', data.title),
    h('span.desc', data.desc),
    h('span.del', { on: { click: [() => {
      del(data)
    }] } }, 'x')
  ])
}

function renderList () {
  return h('div.list',[
    h('ul', data.map(listShow))
  ])
}

function vnode (data) {
  return h('div#app', {
    style: {
      width: '800px',
      margin: '0 auto'
    }
  }, [
    h('h1','Top 5 animation'),
    h('div.left', {
      style: {
        float: 'left'
      }
    }, [
      h('span', 'sort by:'),
      h('span.ordBtn',{
        on: { 'click': [() => {
          sortRank('sn')
        }] }
      }, 'sn'),
      h('span.ordBtn', {
        on: { 'click': [() => {
          sortRank('title')
        }] }
      }, 'title'),
      h('span.ordBtn', {
        on: { 'click': [() => {
          sortRank('desc')
        }] }
      }, 'description'),
      h('span',{
        style: {
            paddingLeft:'30px'
        }
      }, `当前排序规则为:${sortByRule}`)
    ]),
    h('div.right', {
      style: {
        float: 'right'
      }
    }, [
      h('span.ordBtn', {
        on: { click: add }
      }, 'Add')
    ]),
    h('div.clear', {style: {clear: 'both'}}, ''),
    renderList()
  ])
}

let app = document.querySelector('#app')
let oldVnode = patch(app, vnode(data))

// 新增
function add () {
  dataLength++
  let obj = {
    sn: dataLength,
    title: 'title-' + dataLength,
    desc: 'desc-' + dataLength
  }
  data.push(obj)
  oldVnode = patch(oldVnode, vnode(data))
}

// 排序
function sortRank (type, e) {
  sortByRule = type
  data.sort((a, b) => {
    if (a[type] > b[type]) {
      return 1
    } 
    if (a[type] < b[type]) {
      return -1
    }
    return 0
  })
  oldVnode = patch(oldVnode, vnode(data))
}

function del (item) {
    data = data.filter((data) => {
    return data !== item
  })
  oldVnode = patch(oldVnode, vnode(data))
}